<?php
require dirname(__FILE__) . '/../../config.php';
$paysecMapi = new SoapClient('https://mapi.paysec.cz/?wsdl');
$login = 'Pay8763986';
$password = 'KQI2gwg';
$dbAccess = getDBAccessInfo();
$conn = new mysqli($dbAccess[2], $dbAccess[0], $dbAccess[1]);
$conn->select_db($dbAccess[3]);
$conn->set_charset('utf8');

$time = time();
$sql = "
SELECT id, amount, orderedCredits, user
FROM orders
WHERE $time - created < 86400
    AND paymentType = 5
    AND status = 0
";
$result = $conn->query($sql);
while ($row = $result->fetch_array()) {
    try {
        if ($paysecMapi->VerifyTransactionIsPaid($login, $password, $row['id'],
                $row['amount']) == 0) {
            resolveOrder($conn, $row);
        }
    } catch (Exception $e) {}
}

function resolveOrder(mysqli $conn, array $order) {
    $sql = "
UPDATE orders
SET status = 1
WHERE id = {$order['id']}
";
    $conn->query($sql);
    $sql = "
UPDATE visitors
SET account = account + {$order['orderedCredits']}
WHERE user = {$order['user']}
";
    $conn->query($sql);
}

function getDBAccessInfo() {
    $dbAccess = explode(':', Config::DATABASE_ACCESS);
    $dbAccess[2] = explode('@', $dbAccess[1]);
    $dbAccess[1] = $dbAccess[2][0];
    $dbAccess[2] = $dbAccess[2][1];
    $dbAccess[3] = explode('//', $dbAccess[2]);
    $dbAccess[2] = $dbAccess[3][0];
    $dbAccess[3] = $dbAccess[3][1];
    return $dbAccess;
}
?>
